import { Graph, FunctionExt } from '@antv/x6'

/**
 * 显示/隐藏可连接点
 * @param ports 连接点列表
 * @param show
 */
function showPorts(ports: NodeListOf<SVGAElement>, show: boolean) {
  ports.forEach((item) => {
    item.style.visibility = show ? 'visible' : 'hidden'
  })
}
/**
 * 添加基础交互事件
 * @param graph
 */
export function addBaseEvent(graph: Graph) {
  const container = graph.container
  // 节点右键事件开发中...
  graph.on('node:contextmenu', ({ cell, view }) => {
    console.log(view.container, cell)
  })
  // 鼠标移入展示连接点
  graph.on(
    'node:mouseenter',
    FunctionExt.debounce(() => {
      const ports = container.querySelectorAll(
        '.x6-port-body'
      ) as NodeListOf<SVGAElement>
      showPorts(ports, true)
    }),
    500
  )
  // 鼠标移除隐藏连接点
  graph.on('node:mouseleave', () => {
    const ports = container.querySelectorAll(
      '.x6-port-body'
    ) as NodeListOf<SVGAElement>
    showPorts(ports, false)
  })
  // 节点删除
  graph.bindKey('delete', () => {
    const cells = graph.getSelectedCells()
    if (cells.length) {
      graph.removeCells(cells)
    }
  })
}
